import { Card, Row, Col, Typography, Button, Progress, Tag, Statistic, Input, Checkbox, Space, Divider, Tabs, Badge, Spin, Tooltip, message } from '@/utils/antd-imports';
import { PlusOutlined, SearchOutlined, FilterOutlined, FileAddOutlined, SyncOutlined, ClockCircleOutlined, CheckCircleOutlined, DollarOutlined, FileDoneOutlined, FileSyncOutlined, FileProtectOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { projectApi } from '@/api/projectApi';
import { transformProjectCardsForDisplay, getStatusColor, getTypeColor } from '@/utils/projectDataTransform';
















const { Title, Text } = Typography;
const { Search } = Input;
const { TabPane } = Tabs;

const ProjectSettlementList = ({ onProjectSelect }) => {
  const [activeTab, setActiveTab] = useState('participated');
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState([]);
  const [selectedTypes, setSelectedTypes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [participatedProjects, setParticipatedProjects] = useState([]);
  const [createdProjects, setCreatedProjects] = useState([]);
  
  // 加载项目数据
  useEffect(() => {
    loadProjects();
  }, []);

  const loadProjects = async () => {
    setLoading(true);
    try {
      // 使用新的项目卡片API获取数据
      const response = await projectApi.getProjectCards();
      if (response.code === 200) {
        const projects = transformProjectCardsForDisplay(response.data);
        
        // 这里可以根据实际业务逻辑区分"我参与的项目"和"我创建的项目"
        // 暂时将所有项目都显示在两个标签页中
        setParticipatedProjects(projects);
        setCreatedProjects(projects);
      } else {
        message.error('加载项目数据失败：' + response.message);
      }
    } catch (error) {
      console.error('加载项目数据失败：', error);
      message.error('加载项目数据失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 模拟项目数据 - 我参与的项目（作为备用数据）
  const mockParticipatedProjects = [
    {
      id: 1,
      code: 'GACRND-2025-JS0001',
      createDate: '2025.09.01',
      description: '前端开发项目 - 用户管理系统',
      progress: 75,
      status: '验收中',
      deadline: '2025.12.31',
      type: '整包项目',
      manager: '张三',
      totalTasks: 75,
      completedTasks: 56,
      pendingTasks: 19,
      completionRate: 75
    },
    {
      id: 2,
      code: 'GACRND-2025-JS0002',
      createDate: '2025.08.15',
      description: '后端API开发 - 订单管理系统',
      progress: 90,
      status: '待开票',
      deadline: '2025.11.30',
      type: '人力项目',
      manager: '李四',
      totalTasks: 75,
      completedTasks: 68,
      pendingTasks: 7,
      completionRate: 90
    },
    {
      id: 3,
      code: 'GACRND-2025-JS0003',
      createDate: '2025.10.01',
      description: '移动端开发 - 客户关系管理',
      progress: 30,
      status: '未验收',
      deadline: '2026.03.31',
      type: '人力项目',
      manager: '王五',
      totalTasks: 75,
      completedTasks: 23,
      pendingTasks: 52,
      completionRate: 30
    },
    {
      id: 7,
      code: 'GACRND-2025-JS0007',
      createDate: '2025.09.15',
      description: '大数据分析平台开发',
      progress: 60,
      status: '验收中',
      deadline: '2025.12.15',
      type: '整包项目',
      manager: '周九',
      totalTasks: 75,
      completedTasks: 45,
      pendingTasks: 30,
      completionRate: 60
    },
    {
      id: 8,
      code: 'GACRND-2025-JS0008',
      createDate: '2025.10.05',
      description: '云计算平台搭建',
      progress: 25,
      status: '未验收',
      deadline: '2026.04.30',
      type: '人力项目',
      manager: '吴十',
      totalTasks: 75,
      completedTasks: 19,
      pendingTasks: 56,
      completionRate: 25
    }
  ];

  // 模拟项目数据 - 我创建的项目（作为备用数据）
  const mockCreatedProjects = [
    {
      id: 4,
      code: 'GACRND-2025-JS0004',
      createDate: '2025.07.01',
      description: '数据平台建设 - 大数据分析',
      progress: 100,
      status: '已回款',
      deadline: '2025.10.15',
      type: '整包项目',
      manager: '赵六',
      totalTasks: 75,
      completedTasks: 75,
      pendingTasks: 0,
      completionRate: 100
    },
    {
      id: 5,
      code: 'GACRND-2025-JS0005',
      createDate: '2025.09.20',
      description: 'AI智能平台开发',
      progress: 45,
      status: '开票中',
      deadline: '2026.01.31',
      type: '整包项目',
      manager: '钱七',
      totalTasks: 75,
      completedTasks: 34,
      pendingTasks: 41,
      completionRate: 45
    },
    {
      id: 6,
      code: 'GACRND-2025-JS0006',
      createDate: '2025.10.10',
      description: '物联网设备管理系统',
      progress: 15,
      status: '未验收',
      deadline: '2026.02.28',
      type: '人力项目',
      manager: '孙八',
      totalTasks: 75,
      completedTasks: 11,
      pendingTasks: 64,
      completionRate: 15
    },
    {
      id: 9,
      code: 'GACRND-2025-JS0009',
      createDate: '2025.09.25',
      description: '区块链应用开发',
      progress: 80,
      status: '待回款',
      deadline: '2025.12.31',
      type: '整包项目',
      manager: '郑十一',
      totalTasks: 75,
      completedTasks: 60,
      pendingTasks: 15,
      completionRate: 80
    },
    {
      id: 10,
      code: 'GACRND-2025-JS0010',
      createDate: '2025.10.15',
      description: '智能客服系统开发',
      progress: 10,
      status: '未验收',
      deadline: '2026.05.31',
      type: '人力项目',
      manager: '王十二',
      totalTasks: 75,
      completedTasks: 8,
      pendingTasks: 67,
      completionRate: 10
    }
  ];

  // 获取当前标签页的项目数据
  const getCurrentProjects = () => {
    const projects = activeTab === 'participated' ? participatedProjects : createdProjects;
    
    // 根据搜索文本过滤
    let filtered = projects.filter(project => 
      (project.code || '').toLowerCase().includes(searchText.toLowerCase()) ||
      (project.project_name || '').toLowerCase().includes(searchText.toLowerCase()) ||
      (project.description || '').toLowerCase().includes(searchText.toLowerCase()) ||
      (project.manager || '').toLowerCase().includes(searchText.toLowerCase())
    );

    // 根据状态过滤
    if (selectedStatus.length > 0) {
      filtered = filtered.filter(project => selectedStatus.includes(project.status));
    }

    // 根据类型过滤
    if (selectedTypes.length > 0) {
      filtered = filtered.filter(project => selectedTypes.includes(project.type));
    }

    return filtered;
  };

  // 处理点击项目卡片
  const handleProjectClick = (projectId, projectCode, projectName) => {
    if (onProjectSelect) {
      onProjectSelect({
        type: 'settlement-detail',
        projectId: projectId,
        projectCode: projectCode,
        projectName: projectName  // 新增项目名称
      });
    }
  };

  // 使用工具函数获取状态颜色
  // const getStatusColor = (status) => { ... } // 已移到工具函数中

  // 根据状态获取图标
  const getStatusIcon = (status) => {
    const icons = {
      '未验收': <FileAddOutlined />,
      '验收中': <FileSyncOutlined />,
      '待开票': <FileProtectOutlined />,
      '开票中': <FileDoneOutlined />,
      '待回款': <DollarOutlined />,
      '已回款': <CheckCircleOutlined />
    };
    return icons[status] || <FileAddOutlined />;
  };

  // 项目状态选项
  const statusOptions = ['未验收', '验收中', '待开票', '开票中', '待回款', '已回款'];
  
  // 项目类型选项
  const typeOptions = ['整包项目', '人力项目'];

  // 统计各状态项目数量
  const getStatusCounts = () => {
    const projects = activeTab === 'participated' ? participatedProjects : createdProjects;
    const counts = {
      '未验收': 0,
      '验收中': 0,
      '待开票': 0,
      '开票中': 0,
      '待回款': 0,
      '已回款': 0
    };
    
    projects.forEach(project => {
      counts[project.status]++;
    });
    
    return counts;
  };

  // 处理状态指标点击
  const handleStatusClick = (status) => {
    if (selectedStatus.includes(status)) {
      setSelectedStatus(selectedStatus.filter(s => s !== status));
    } else {
      setSelectedStatus([...selectedStatus, status]);
    }
  };

  // 渲染状态指标卡片
  const renderStatusIndicator = (status, count, icon) => {
    const isActive = selectedStatus.includes(status);
    
    return (
      <Card 
        hoverable
        style={{
          width: '100%',
          border: isActive ? `1px solid ${getStatusColor(status)}` : '1px solid #f0f0f0',
          background: isActive ? '#f6ffed' : '#fff',
          cursor: 'pointer',
          transition: 'all 0.3s'
        }}
        bodyStyle={{
          padding: '12px 16px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}
        onClick={() => handleStatusClick(status)}
      >
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{
            width: 36,
            height: 36,
            borderRadius: '50%',
            background: isActive ? getStatusColor(status) : '#f5f5f5',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: 12,
            color: isActive ? '#fff' : getStatusColor(status)
          }}>
            {icon}
          </div>
          <div>
            <Text style={{ fontSize: 14, color: '#666' }}>{status}</Text>
            <Text strong style={{ display: 'block', fontSize: 18, color: isActive ? getStatusColor(status) : '#333' }}>
              {count}
            </Text>
          </div>
        </div>
        {isActive && (
          <CheckCircleOutlined style={{ color: getStatusColor(status), fontSize: 18 }} />
        )}
      </Card>
    );
  };

  // 自定义任务进度条渲染
  const customTaskProgress = (completed, pending) => {
    const total = completed + pending;
    const completedPercent = total > 0 ? Math.round((completed / total) * 100) : 0;
    const pendingPercent = total > 0 ? Math.round((pending / total) * 100) : 0;
    
    return (
      <div style={{ position: 'relative', height: 8, background: '#f5f5f5', borderRadius: 4, marginBottom: 8 }}>
        <Tooltip title={`已完成: ${completed}个任务`}>
          <div 
            style={{
              position: 'absolute',
              left: 0,
              width: `${completedPercent}%`,
              height: '100%',
              background: '#52c41a',
              borderRadius: completedPercent === 100 ? '4px' : '4px 0 0 4px'
            }}
          />
        </Tooltip>
        <Tooltip title={`未完成: ${pending}个任务`}>
          <div 
            style={{
              position: 'absolute',
              right: 0,
              width: `${pendingPercent}%`,
              height: '100%',
              background: '#fa541c',
              borderRadius: completedPercent === 0 ? '4px' : '0 4px 4px 0'
            }}
          />
        </Tooltip>
      </div>
    );
  };

  // 渲染项目卡片
  const renderProjectCard = (project) => (
    <Card 
      style={{ 
        height: '100%',
        borderRadius: 8,
        border: '1px solid #e8e8e8',
        boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
        transition: 'all 0.3s'
      }}
      bodyStyle={{ 
        height: '100%',
        padding: 16,
        display: 'flex',
        flexDirection: 'column'
      }}
      hoverable
      onClick={() => handleProjectClick(project.id, project.code, project.project_name)}
      className="project-card"
    >
      <div style={{ flex: 1 }}>
        <div style={{ marginBottom: 12 }}>
          <Text strong style={{ fontSize: 24, lineHeight: 1.4, display: 'block', marginBottom: 4 }}>
            {project.project_name}
          </Text>
          <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 8 }}>
            {project.code}
          </Text>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <Tag color={getTypeColor(project.type)} style={{ margin: 0, fontSize: 10 }}>
              {project.type}
            </Tag>
            <Tag color={getStatusColor(project.status)} style={{ margin: 0, fontSize: 10 }}>
              {project.status}
            </Tag>
          </div>
        </div>

        <div style={{ marginBottom: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
            <Text style={{ fontSize: 12, color: '#666' }}>创建：{project.createDate}</Text>
            <Text style={{ fontSize: 12, color: '#666' }}>截止：{project.deadline}</Text>
          </div>
          <Text style={{ fontSize: 12, color: '#666' }}>项目经理：{project.manager}</Text>
        </div>

        {/* 自定义任务进度条 */}
        {customTaskProgress(project.completedTasks || 0, project.pendingTasks || 0)}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ display: 'flex', gap: 16 }}>
          <div style={{ textAlign: 'center' }}>
            <Text strong style={{ display: 'block', fontSize: 14, color: '#1890ff' }}>{project.totalTasks}</Text>
            <Text style={{ fontSize: 10, color: '#999' }}>任务数</Text>
          </div>
          <div style={{ textAlign: 'center' }}>
            <Text strong style={{ display: 'block', fontSize: 14, color: '#52c41a' }}>{project.completedTasks}</Text>
            <Text style={{ fontSize: 10, color: '#999' }}>已完成</Text>
          </div>
          <div style={{ textAlign: 'center' }}>
            <Text strong style={{ display: 'block', fontSize: 14, color: '#fa541c' }}>{project.pendingTasks}</Text>
            <Text style={{ fontSize: 10, color: '#999' }}>未完成</Text>
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <Text strong style={{ display: 'block', fontSize: 16, color: '#1890ff' }}>
            {project.completionRate}%
          </Text>
          <Text style={{ fontSize: 10, color: '#999' }}>完成率</Text>
        </div>
      </div>
    </Card>
  );

  // 渲染项目列表视图
  const renderProjectListView = () => {
    if (loading) {
      return (
        <div style={{ 
          background: '#fff', 
          padding: 24, 
          borderRadius: 8, 
          minHeight: 'calc(100vh - 48px)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center'
        }}>
          <Spin size="large" />
        </div>
      );
    }

    const currentProjects = getCurrentProjects();
    const allProjects = currentProjects;
    
    const statusCounts = getStatusCounts();

    return (
      <div style={{ background: '#fff', padding: 24, borderRadius: 8, minHeight: 'calc(100vh - 48px)' }}>

        {/* 标签页 */}
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          style={{ marginBottom: 24 }}
        >
          <TabPane tab="我参与的项目" key="participated" />
          <TabPane tab="我创建的项目" key="created" />
        </Tabs>

        {/* 状态指标区域 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} md={6}>
            {renderStatusIndicator('未验收', statusCounts['未验收'], getStatusIcon('未验收'))}
          </Col>
          <Col xs={24} sm={12} md={6}>
            {renderStatusIndicator('验收中', statusCounts['验收中'], getStatusIcon('验收中'))}
          </Col>
          <Col xs={24} sm={12} md={6}>
            {renderStatusIndicator('待开票', statusCounts['待开票'], getStatusIcon('待开票'))}
          </Col>
          <Col xs={24} sm={12} md={6}>
            {renderStatusIndicator('开票中', statusCounts['开票中'], getStatusIcon('开票中'))}
          </Col>
          <Col xs={24} sm={12} md={6}>
            {renderStatusIndicator('待回款', statusCounts['待回款'], getStatusIcon('待回款'))}
          </Col>
          <Col xs={24} sm={12} md={6}>
            {renderStatusIndicator('已回款', statusCounts['已回款'], getStatusIcon('已回款'))}
          </Col>
        </Row>

        {/* 筛选条件区域 */}
        <Card 
          style={{ marginBottom: 24, background: '#fafafa' }}
          bodyStyle={{ padding: 16 }}
        >
          <Row gutter={[16, 16]} align="middle">
            <Col xs={24} sm={12} md={8} lg={6}>
              <div>
                <Text strong style={{ display: 'block', marginBottom: 8, fontSize: 12 }}>项目类型</Text>
                <Checkbox.Group 
                  options={typeOptions} 
                  value={selectedTypes}
                  onChange={setSelectedTypes}
                  style={{ width: '100%' }}
                >
                  <Row gutter={[8, 8]}>
                    {typeOptions.map(type => (
                      <Col span={24} key={type}>
                        <Checkbox value={type} style={{ fontSize: 12 }}>{type}</Checkbox>
                      </Col>
                    ))}
                  </Row>
                </Checkbox.Group>
              </div>
            </Col>
            
            <Col xs={24} sm={12} md={8} lg={6}>
              <div>
                <Text strong style={{ display: 'block', marginBottom: 8, fontSize: 12 }}>查询项目</Text>
                <Search
                  placeholder="输入项目编号、名称或描述"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  style={{ width: '100%' }}
                  size="small"
                />
              </div>
            </Col>
          </Row>
        </Card>

        {/* 项目列表 */}
        <Row gutter={[24, 24]}>
          {allProjects.map((project, index) => (
            <Col key={project.id || index} xs={24} sm={12} md={8} lg={6}>
              {renderProjectCard(project)}
            </Col>
          ))}
        </Row>
      </div>
    );
  };

  return renderProjectListView();
};

export default ProjectSettlementList;